//
//  VideoPlayerController.swift
//  VideoPlayer
//
//  Created by JY_NEW on 2021/10/11.
//

import Foundation
import UIKit

open class VideoPlayerViewController: UIViewController {
    public let player = VideoPlayerManager()
    
    /// 在阻断时要播放的时间，等于阻断结束再启动
    var isNeedToPlayAtBlocking: Bool = false
    var blockingPlayTime: TimeInterval?
    /// 看不见时临时暂停
    var disappearPauseFlag = makePauseFlag()
    /// 退出全屏标志
    var quitFullScreenFlags: [Int] = []
    /// 退到后台时退出全屏标记
    var isFullScreenBeforeEnterBackground = false
    
    open override func loadView() {
        self.view = self.player.view
    }
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        
        self.player.layerManager.observer.layerStatus.addTarget(self, action: #selector(self.onLayerStatusChanged))
        
        NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive), name: UIApplication.willResignActiveNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
    }
    deinit {
        self.player.layerManager.observer.layerStatus.removeTarget(self)
        NotificationCenter.default.removeObserver(self)
    }
    open override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.play(for: self.disappearPauseFlag)
    }

    open override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.pause(for: self.disappearPauseFlag)
    }
    
    // 有阻断层时不给播放
    @objc func onLayerStatusChanged() {
        if !self.checkIsBlocked() {
            if self.isNeedToPlayAtBlocking {
                self.isNeedToPlayAtBlocking = false
                if let blockingPlayTime = blockingPlayTime {
                    self.player.play(from: blockingPlayTime)
                }else{
                    self.player.play()
                }
            }
        }
    }
    
    func checkIsBlocked() -> Bool {
        return self.player.layerManager.layers.blocks.contains(where: { $0.status.isActived })
    }
    
    open override var shouldAutorotate: Bool {
        return self.player.shouldAutorotate
    }
    
    open override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .all
    }
    open override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return .portrait
    }
    
    public var url: URL? {
        return self.player.url
    }
    
    public var status: VideoPlayerStatus {
        return self.player.status
    }
    
    public var isFullScreen: Bool {
        get {
            return self.player.isFullScreen
        }
        set {
            self.quitFullScreenFlags.removeAll()
            self.player.isFullScreen = newValue
        }
    }
    public var currentTime: TimeInterval {
        return self.player.currentTime
    }
    
    public var duration: TimeInterval {
        return self.player.duration
    }
    
    /// 加载链接，播放前需要调用
    open func load(url: URL) {
        self.player.url = url
    }
    /// 播放
    @discardableResult
    open func play() -> Bool {
        if self.checkIsBlocked() {
            self.isNeedToPlayAtBlocking = true
            self.blockingPlayTime = nil
            return false
        }else{
            self.isNeedToPlayAtBlocking = false
            self.player.play()
            return true
        }
    }
    /// 播放
    @discardableResult
    open func play(from time: TimeInterval) -> Bool {
        if self.checkIsBlocked() {
            self.isNeedToPlayAtBlocking = true
            self.blockingPlayTime = time
            return false
        }else{
            self.isNeedToPlayAtBlocking = false
            self.player.play(from: time)
            return true
        }
    }
    /// 播放指定链接
    open func play(for url: URL, from time: TimeInterval = 0) {
        self.load(url: url)
        if time > 0 {
            self.play(from: time)
        }else{
            self.play()
        }
    }
    /// 暂停
    open func pause() {
        self.player.pause()
    }
    
    public func play(for flag: Int) {
        self.player.play(for: flag)
    }
    
    public func pause(for flag: Int) {
        self.player.pause(for: flag)
    }
    public func setFullScreen(_ isFullScreen: Bool, completion: @escaping () -> Void) {
        if self.isFullScreen != isFullScreen {
            self.player.isFullScreen = isFullScreen
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.25, execute: completion)
        }else{
            completion()
        }
    }
    /// 根据标志回到全屏
    public func returnFullScreen(for flag: Int) {
        if let idx = self.quitFullScreenFlags.firstIndex(of: flag) {
            self.quitFullScreenFlags.remove(at: idx)
            if self.quitFullScreenFlags.count == 0 && !self.isFullScreen {
                self.player.isFullScreen = true
            }
        }
    }
    /// 根据标志退出全屏
    public func quitFullScreen(for flag: Int, completion: @escaping () -> Void) {
        if self.isFullScreen {
            if !self.quitFullScreenFlags.contains(flag) {
                self.quitFullScreenFlags.append(flag)
                self.setFullScreen(false) { [weak self] in
                    if !(self?.isFullScreen ?? true) {
                        completion()
                    }
                }
            }else{
                completion()
            }
        }else{
            completion()
        }
    }
    @objc func applicationWillResignActive() {
        self.isFullScreenBeforeEnterBackground = self.player.isFullScreen
    }
    @objc func applicationDidBecomeActive() {
        if self.isFullScreenBeforeEnterBackground && !self.player.isFullScreen {
            self.player.isFullScreen = true
        }
    }
}

// MARK: 自动生成退出全屏标识

fileprivate var __video_player_last_auto_quit_fullscreen_flag = Int.max
///自动生成不重复的暂停标识
public func makeQuitFullScreenFlag() -> Int {
    __video_player_last_auto_quit_fullscreen_flag -= 1
    return __video_player_last_auto_quit_fullscreen_flag
}
